<?php

namespace App\Http\Controllers\Api;

use App\Http\Resources\Products;
use App\Models\Product;
use App\Services\Api;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ProductController extends Controller
{
    /**
     * 商品列表
     */
    public function index(Request $request)
    {
        $data = $request->all([
            'page', 'limit',
            'category',
            'categories', 'ids',
            'keyword',
            'price', // 价格排序： asc / desc
            'publish', // 上架时间: asc / desc
            'sales', // 销量: asc / desc
        ]);

        $categories = json_decode($data['categories'], true);
        $ids = json_decode($data['ids'], true);

        $page = $request->input('page', 1) ?: 1;
        $limit = $request->input('limit', 10) ?: 10;

        $skip = ($page - 1) * $limit;

        $query = Product::query()->whereStatus(1);

        $query->when($data['category'], function (Builder $query, $value) {
            $query->whereCategoryId($value);
        });

        $query->where(function (Builder $query) use ($categories, $ids) {
            $query->when($categories, function (Builder $query, $value) {
                $query->orWhereIn('category_id', $value);
            });
            $query->when($ids, function (Builder $query, $value) {
                $query->orWhereIn('id', $value);
            });
        });

        $query->when($data['keyword'], function (Builder $query, $value) {
            $query->where('name', 'like', "%{$value}%");
        });

        if ($data['price'] || $data['publish'] || $data['sales']) {
            $field = $data['price'] ? 'price->original' : ($data['publish'] ? 'updated_at' : ($data['sales'] ? 'count_sales' : ''));

            $direct = $data['price'] ?: $data['publish'] ?: $data['sales'];

            if (strtolower($direct) == 'asc') {
                $query->orderBy($field, 'asc');
            } else {
                $query->orderBy($field, 'desc');
            }
        }

        $total = $query->count();
        $products = $query->skip($skip)->limit($limit)->get();

        return Api::msg('api.product.index', [
            'total' => $total,
            'result' => Products::collection($products),
        ]);
    }

    /**
     * 商品详情
     */
    public function show(Request $request)
    {
        $id = $request->input('id');

        $product = Product::query()->find($id);

        if (!$product) {
            return Api::msg('api.product.not_found');
        }

        // 添加浏览量
        $product->increment('count_reviews');

        return Api::msg('api.product.show', $product->display());
    }
}
